package com.lightbend.akka.sample

import akka.actor.typed.scaladsl.{AbstractBehavior, ActorContext, Behaviors}
import akka.actor.typed.{ActorRef, Behavior, PostStop, Signal}
import com.lightbend.akka.sample.Device.{Command, Passivate, ReadTemperature, RecordTemperature, RespondTemperature, TemperatureRecorded}

object Device {

  def apply(groupId: String, deviceId: String): Behavior[Command] = Behaviors.setup(context => new Device(context, groupId, deviceId))

  sealed trait Command
  final case class ReadTemperature(requestId: Long,replyTo:ActorRef[RespondTemperature]) extends Command
  final case class RespondTemperature(requestId: Long, value: Option[Double])

  final case class RecordTemperature(requestId: Long, value: Double, replyTo: ActorRef[TemperatureRecorded]) extends Command

  final case class TemperatureRecorded(requestId: Long)

  case object Passivate extends Command

}

class Device(context:ActorContext[Command], groupId:String, deviceId: String) extends AbstractBehavior[Command](context = context){

  var lastTemperatureReading :Option[Double] = None

  override def onMessage(msg: Command): Behavior[Command] = {
    msg match {
      case ReadTemperature(requestId, replyTo) =>
        replyTo ! RespondTemperature(requestId, lastTemperatureReading)
        this
      case RecordTemperature(requestId, value, replyTo) =>
        context.log.info("record temperature reading {} with {}", value, requestId)
        lastTemperatureReading = Some(value)
        replyTo ! TemperatureRecorded(requestId)
        this
      case Passivate =>
        Behaviors.stopped

    }
  }

  override def onSignal: PartialFunction[Signal, Behavior[Command]] = {
    case stop: PostStop =>
      context.log.info("Device actor {}-{} stopped", groupId, deviceId)
      this
  }
}
